<?php

declare(strict_types=1);
/*
 * @Description: 友盟service类
 * @Author: QianLong
 * @Date: 2019-10-13 12:39:05
 * @LastEditors    : QianLong
 * @LastEditTime   : 2023-03-10 17:20:04
 */

namespace App\Service\Push;

use App\Common\RedisCache;
use Yurun\Util\HttpRequest;

class JiGuang
{
    protected $serverInfo = [];
    public function __construct($serverInfo)
    {
        $this->serverInfo = $serverInfo;
    }
    /**
     * 单条推送 打开页面
     * 
     */
    public function singlePushStartPage(?array $data = null)
    {
        $return['send_result'] = false;
        if (!empty($data) && is_array($data)) {
            $url = 'https://api.jpush.cn/v3/push';
            $post['platform'] = 'all';
            $extras = [];
            if (isset($data['click_type_content']) && !empty($data['click_type_content'])) {
                $extras = json_decode($data['click_type_content'],true);
            }
            $post['options']['apns_production'] = true;
            // $post['options']['alternate_set'] = true;
            $post['inapp_message']['inapp_message'] = true;
            $post['audience'] = $data['single_cid'];
            $post['notification']['android']['alert'] = $data['content'];
            // $post['notification']['android']['alternate_alert'] = $data['title'];
            // $post['notification']['android']['alternate_title'] = $data['content'];
            $post['notification']['android']['title'] = $data['title'];
            $post['notification']['android']['extras'] = $extras;
            $post['notification']['android']['extras']['third_url_encode'] = true;
            $post['notification']['ios']['alert'] = $data['content'];
            // $post['notification']['ios']['alternate_alert'] = $data['title'];
            $post['notification']['ios']['extras'] = $extras;
            $post['notification']['ios']['extras']['third_url_encode'] = true;
            $http = new HttpRequest;
            $sign = $this->getSign($url, $post);
            $response = $http->header('Authorization',$sign)->post($url, $post, 'json');
            $responseData = json_decode($response->body(), true);
            $return['send_result_data'] = $responseData;
            $return['pushParam'] = $post;
            $return['task_id'] = '';
            if (isset($responseData['ret']) && strtoupper($responseData['ret']) == 'SUCCESS') {
                $return['send_result'] = true;
                $return['send_error'] = '';
                $return['task_id'] = $responseData['data']['msg_id'];
            }else{
                $return['send_error'] = '(' . $responseData['error']['code'] . ') ' . $responseData['error']['message'];
            }
            unset($post,$url,$response,$pushData,$http,$data);
            return $return;
        }
    }
    private function getSign()
    {
        $signStr = base64_encode($this->serverInfo['jiguang_app_key'] .':'. $this->serverInfo['jiguang_master_secret']);
        return 'Basic '.$signStr;
    }
}
